package c1;

/**
 * 其中一种结果：
 * Thread[Thread-0,5,main] yield cpu...
 * Thread[Thread-0,5,main] is over
 * Thread[Thread-2,5,main] yield cpu...
 * Thread[Thread-1,5,main] yield cpu...
 * Thread[Thread-2,5,main] is over
 * Thread[Thread-1,5,main] is over
 *
 * 调用yield方法，让出自己剩余的时间片，所以没有按照顺序输出
 *
 */
public class YieldTest implements Runnable{
    YieldTest(){
        //创建并启动线程
        Thread t=new Thread(this);
        t.start();
    }
    @Override
    public void run() {
        for(int i=0;i<5;i++){
            //当i=0时让出CPU执行权，放弃时间片，进行下一轮调度
            if(i%5==0){
                System.out.println(Thread.currentThread()+" yield cpu...");
            }
            Thread.yield();
        }
        System.out.println(Thread.currentThread()+" is over");
    }

    public static void main(String[] args){
        new YieldTest();
        new YieldTest();
        new YieldTest();
    }
}
